import React, { useState, useCallback, useMemo, useRef } from 'react'
import { useMouse, useThrottle } from 'ahooks'

import SvgIcon from '../../common/svg-icon'
import Progress from '../../common/progress'
import video from '../../../store/video'
import scss from './volume.module.scss'
import useSubs from '../../../hooks/useSubs'
import { outOfArea } from '@/util/index'

const customStyle = {
  bar: {
    borderRadius: 5,
  },
  progress: {
    borderRadius: 5,
  },
}
const progress = {
  height: 105,
  width: 5,
}

const Volume = () => {
  const [visible, setVisible] = useState(false)
  const [volumeVal, setVolumeVal] = useState(0)
  const [initVal, setInitVal] = useState()
  const [progressLen, setProgressLen] = useState(0)
  const [pct, setPct] = useState(0)
  const [slient, setSlient] = useState(true)

  const optRef = useRef()
  const btnRef = useRef()
  const wrapRef = useRef()

  const mouse = useMouse()
  const throttledValue = useThrottle(mouse, { wait: 200 })

  const progressRef = useCallback((val) => {
    setPct(val?.pct ?? 0)
  })

  useMemo(() => {
    setVolumeVal(Math.floor(100 * pct))
  }, [pct])

  useMemo(() => {
    videoVolume('set', pct.toFixed(2))
  }, [volumeVal])

  useMemo(() => {
    if (visible) {
      if (outOfArea(optRef.current, throttledValue) && outOfArea(btnRef.current, throttledValue)) {
        setVisible(false)
      }
    }
  }, [throttledValue])

  useMemo(() => {
    videoVolume('set', slient ? 0 : pct.toFixed(2))
  }, [slient])

  useSubs(({ action, val }) => {
    if (action === 'initVolume') {
      setInitVal(val * 100)
      setProgressLen(progress.height * val)
    }
  })

  function videoVolume(action, val) {
    const screen = video.findScreenById(video.curScreenId)
    if (screen) {
      const video = screen?.player?.video
      if (video && action === 'set') {
        video.volume = val
      }
    }
    return video.volume
  }

  return (
    <div style={{ position: 'relative' }}>
      <div style={{ display: visible && !slient ? 'flex' : 'none' }} className={scss.panel} ref={optRef}>
        <span className={scss.text}>{volumeVal}</span>
        <div ref={wrapRef} className={scss.wrap}>
          <Progress
            ref={progressRef}
            type="vertical"
            width={progress.width}
            height={progress.height}
            borderRadius={5}
            reverse
            customStyle={customStyle}
            progressLen={progressLen}
          />
        </div>
      </div>
      <div onMouseOver={() => setVisible(true)} ref={btnRef}>
        <SvgIcon icon={slient ? '#iconslient' : '#iconvolume'} handleClick={() => setSlient(!slient)} />
      </div>
    </div>
  )
}

export default Volume
